import unittest
import os
import shutil
from io import StringIO
from unittest.mock import patch
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from Main import count_characters, count_words, count_lines

class TestMain(unittest.TestCase):

    def setUp(self):
        # 创建临时文件夹用于测试
        self.test_dir = "test_files"
        os.makedirs(self.test_dir, exist_ok=True)

        # 创建空文件
        self.empty_file = os.path.join(self.test_dir, "test_file_empty.txt")
        open(self.empty_file, 'a').close()

        # 创建包含字符的文件
        self.chars_file = os.path.join(self.test_dir, "test_file_chars.txt")
        with open(self.chars_file, 'w') as f:
            f.write("abcdefg")

        # 创建包含单词的文件
        self.words_file = os.path.join(self.test_dir, "test_file_words.txt")
        with open(self.words_file, 'w') as f:
            f.write("one two three four five")

        # 创建包含代码行、空行和注释行的文件
        self.lines_file = os.path.join(self.test_dir, "test_file_lines.txt")
        with open(self.lines_file, 'w') as f:
            f.write("# This is a comment\n")       # 注释行
            f.write("print('Hello')\n")           # 代码行
            f.write("\n")                         # 空行
            f.write("// This is also a comment\n")# 注释行
            f.write("x = 1 + 2\n")                # 代码行
            f.write("y = 3 * 4\n")                # 代码行
            f.write("\n")                         # 空行
            f.write("# Another comment\n")        # 注释行
            f.write("z = x + y\n")                # 代码行


    def tearDown(self):
        # 删除测试文件夹及其内容
        shutil.rmtree(self.test_dir)

    def test_count_characters(self):
        self.assertEqual(count_characters(self.empty_file), 0)
        self.assertEqual(count_characters(self.chars_file), 7)

    def test_count_words(self):
        self.assertEqual(count_words(self.empty_file), 0)
        self.assertEqual(count_words(self.words_file), 5)

    def test_count_lines(self):
        # 验证代码行、空行和注释行的统计
        expected = {'code_lines': 4, 'empty_lines': 2, 'comment_lines': 3}
        result = count_lines(self.lines_file)
        self.assertEqual(result, expected)

if __name__ == '__main__':
    unittest.main()